package com.zksw.controller;

import com.alibaba.fastjson.JSON;
import com.zksw.constant.ConfigConstant;
import com.zksw.constant.Constant;
import com.zksw.entity.SysOssEntity;
import com.zksw.oss.CloudStorageConfig;
import com.zksw.service.SysConfigService;
import com.zksw.service.SysOssService;
import com.zksw.utils.*;
import com.zksw.validator.ValidatorUtils;
import com.zksw.validator.group.AliyunGroup;
import com.zksw.validator.group.QcloudGroup;
import com.zksw.validator.group.QiniuGroup;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.*;
import java.util.*;


/**
 * 文件上传
 *
 * @author lipengjun
 * @email 939961241@qq.com
 * @date 2017-03-25 12:13:26
 */
@RestController
@RequestMapping("sys/oss")
public class SysOssController {
    @Autowired
    private SysOssService sysOssService;
    @Autowired
    private SysConfigService sysConfigService;

    private final static String KEY = ConfigConstant.CLOUD_STORAGE_CONFIG_KEY;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:oss:all")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<SysOssEntity> sysOssList = sysOssService.queryList(query);
        int total = sysOssService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(sysOssList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 云存储配置信息
     */
    @RequestMapping("/config")
    @RequiresPermissions("sys:oss:all")
    public R config() {
        CloudStorageConfig config = sysConfigService.getConfigObject(KEY, CloudStorageConfig.class);

        return R.ok().put("config", config);
    }


    /**
     * 保存云存储配置信息
     */
    @RequestMapping("/saveConfig")
    @RequiresPermissions("sys:oss:all")
    public R saveConfig(@RequestBody CloudStorageConfig config) {
        //校验类型
        ValidatorUtils.validateEntity(config);

        if (config.getType() == Constant.CloudService.QINIU.getValue()) {
            //校验七牛数据
            ValidatorUtils.validateEntity(config, QiniuGroup.class);
        } else if (config.getType() == Constant.CloudService.ALIYUN.getValue()) {
            //校验阿里云数据
            ValidatorUtils.validateEntity(config, AliyunGroup.class);
        } else if (config.getType() == Constant.CloudService.QCLOUD.getValue()) {
            //校验腾讯云数据
            ValidatorUtils.validateEntity(config, QcloudGroup.class);
        }


        sysConfigService.updateValueByKey(KEY, JSON.toJSONString(config));

        return R.ok();
    }


    /**
     * 上传文件
     */
    @RequestMapping("/upload")
    @RequiresPermissions("sys:oss:all")
    public R upload(@RequestParam("file") MultipartFile file, String fileType, HttpServletRequest request) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        R r = null;
        HttpSession httpSession = request.getSession();
        if(httpSession.getAttribute("appId") != null){
            String appId = httpSession.getAttribute("appId").toString();
            String webUrl = ResourceUtil.getConfigByName("nginx.file.host");
            String rootDir = ResourceUtil.getConfigByName("nginx.file.root.dir");
            if(StringUtils.isNotEmpty(fileType)){
                rootDir = rootDir + "/" + fileType + "/";
                webUrl = webUrl  + "/" + fileType + "/";
            }

            String fileDir = "/" + appId + "/";
            String fileName = UUID.randomUUID().toString()  + "_" + file.getOriginalFilename();
            File dir = new File(rootDir + fileDir);
            if(!dir.exists()){
                dir.mkdirs();
            }
            String filePath = fileDir + fileName;
            File saveFile = new File(rootDir + filePath);
            FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile);
            SysOssEntity ossEntity = new SysOssEntity();
            ossEntity.setUrl(webUrl + filePath);
            ossEntity.setCreateDate(new Date());
            sysOssService.save(ossEntity);

            r = new R();
            r.put("url", webUrl + filePath);
            r.put("link", webUrl + filePath);
            return r;
        }else{
            r = new R();
            return R.error("appId is null");
        }
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:oss:all")
    public R delete(@RequestBody Long[] ids) {
        sysOssService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查询所有列表
     */
    @RequestMapping("/queryAll")
    public List<String> queryAll(@RequestParam Map<String, Object> params) {
        //查询列表数据
        List<SysOssEntity> sysOssList = sysOssService.queryList(params);

        List<String> list = new ArrayList<>();
        if (null != sysOssList && sysOssList.size() > 0) {
            for (SysOssEntity item : sysOssList) {
                list.add(item.getUrl());
            }
        }
        return list;
    }
    /**
     * 查看所有列表
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public R uploadFile(@Param("payImage") MultipartFile payImage, HttpServletRequest request) {
        R res = null;
        try {
            String webUrl = ResourceUtil.getConfigByName("nginx.file.host");
            String rootDir = ResourceUtil.getConfigByName("nginx.file.root.dir");
            String fileDir = "/" + "wx_appid";
            String fileName = UUID.randomUUID().toString()  + "_" + payImage.getOriginalFilename();

          /*  String webappPath = this.getClass().getResource("/").getPath()
                    .replaceFirst("/", "").replaceAll("WEB-INF/classes/", "");

            String savePathDir = File.separatorChar + "statics" +
                    File.separatorChar + "oss_img"
                    + File.separatorChar + UUID.randomUUID().toString() + File.separatorChar;*/
            File dir = new File(rootDir + fileDir);
            if(dir.exists()){
                dir.mkdirs();
            }
            String filePath = fileDir + fileName;
            FileUtils.copyInputStreamToFile(payImage.getInputStream(),new File(rootDir + filePath));

            res = R.ok().put("path", webUrl + filePath);
            SysOssEntity ossEntity = new SysOssEntity();
            ossEntity.setUrl(webUrl + filePath);
            ossEntity.setCreateDate(new Date());
            sysOssService.save(ossEntity);

        } catch (IOException e) {
            e.printStackTrace();
            res = R.error(e.getMessage());
        }
        return res;
    }



    public static void main(String[] args) throws Exception {


    }
}
